package com.study.websocket2.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 */
@Slf4j
@Service
public class DefaultMessageHandler {

    private static Map<String, String> deviceToSessionMap = new HashMap<>();
    private static Map<String, String> sessionIdToDeviceMap = new HashMap<>();
    private static Map<String, String> resultCache = new HashMap<>();

    //接收消息处理方法
    public void process(String msg, String sessionId) {
        log.info("接收到设备 :" + sessionIdToDeviceMap.get(sessionId) + " 的消息：" + msg);
        String deviceId = sessionIdToDeviceMap.get(sessionId);
        resultCache.put(deviceId, msg);
    }

    //处理登陆流程做设备注册
    public boolean deLogin(String msg, String sessionId) {
        log.info("接收到的登陆消息 :" + msg);
        String deviceId = msg;
        //重新绑定关系
        deviceToSessionMap.put(deviceId, sessionId);
        sessionIdToDeviceMap.put(sessionId, deviceId);
        return true;
    }

    //处理连接断开的回收数据处理
    public void sessionClose(String sessionId) {
        String deviceId = sessionIdToDeviceMap.get(sessionId);
        deviceToSessionMap.remove(deviceId);
        sessionIdToDeviceMap.remove(sessionId);

        //TODO: 通知上层进行设备状态变更
    }

    //进行消息发送
    public String SySendMsg(String deviceId, String msg) {
        Integer time = 0;
        String sessionId = deviceToSessionMap.get(deviceId);
        try {
            WebSocketServer.sendMsg(msg, sessionId);
            //需要接收到返回数据才进行返回
            while (true) {
                Thread.sleep(1000);
                //获取缓存消息
                String result = resultCache.get(deviceId);
                if (result != null) {
                    resultCache.remove(deviceId);
                    return result;
                } else {
                    //尝试获取3次
                    if (time > 3) {
                        return null;
                    }
                    time = time + 1;
                }
            }
        } catch (InterruptedException e) {
            log.info("等待超时 ");
        } catch (IOException e) {
            log.info("发送消息失败 :" + msg + ",设备id:" + deviceId);
        }
        return null;
    }

    //进行消息发送
    public void sendMsg(String deviceId, String msg) {
        String sessionId = deviceToSessionMap.get(deviceId);
        try {
            WebSocketServer.sendMsg(msg, sessionId);
        } catch (IOException e) {
            log.info("发送消息失败 :" + msg + ",设备id:" + deviceId);
        }
    }
}
